﻿using System.Text.RegularExpressions;
using RAP.Framework.Libary.DomTemplateBuilder.Element.Conditional;
using RAP.Framework.Libary.Utils;
using RAP.Framework.Libary.DomTemplateBuilder.Interface;

namespace RAP.Framework.Libary.DomTemplateBuilder.Handler.Conditional
{
	/// <summary>
	/// 正则表达式匹配的Handler
	/// </summary>
	public class RegexIsMatchHandler : ConditionalHandler
	{
		/// <summary>
		/// Handler对应的配置节点
		/// </summary>
		public virtual new RegexIsMatch Element
		{
			get
			{
				return base.Element as RegexIsMatch;
			}
			set
			{
				base.Element = value as ConditionalBase;
			}
		}

		public override bool IsCondition ( object rootParamObject, object parentParamObject, ITemplateRenderContext context )
		{
			var value = this.GetPropertyValue ( rootParamObject, parentParamObject, context );

			if ( value == null )
			{
				return false;
			}
			var expression = this.GetExpressionValue ( this.Element.Expression, rootParamObject, parentParamObject, context ) as string;
			if ( expression.IsNullOrEmpty ( ) )
			{
				return false;
			}
			return Regex.IsMatch ( value.ToString ( ), expression );
		}

		protected override bool DoCompareValue ( object propertyValue, object rootParamObject, object parentParamObject, ITemplateRenderContext context )
		{
			if ( propertyValue == null )
			{
				return false;
			}
			var expression = this.GetExpressionValue ( this.Element.Expression, rootParamObject, parentParamObject, context ) as string;
			if ( expression.IsNullOrEmpty ( ) )
			{
				return false;
			}
			return Regex.IsMatch ( propertyValue.ToString ( ), expression );
		}
	}
}
